/**
 * HttpServletResponse 响应输出工具
 * @author lms 2022.07.15
 */
package ms.core.common.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import ms.core.common.ApiResult;
import ms.core.tool.Log4j2Tool;

public class ResponseUtils {

	public static void doResponse(HttpServletResponse resp, int code, ApiResult result) {
		doResponse(resp, code, result==null ? "" : result.toString());
	}

	public static void doResponse(HttpServletResponse resp, int code, String content) {
		try{
			resp.setStatus(code);
			resp.setContentType("application/json;charset=utf-8"); 
			PrintWriter out = resp.getWriter();
			out.write(content);
			out.flush();
			out.close();
		}catch(IOException e){
			Log4j2Tool.error(ResponseUtils.class, "doResponse:", e);
		}
	}
	
	/**
	 * 输出字节流
	 * 
	 * @param resp
	 * @param code
	 * @param buf
	 */
	public static void doResponse(HttpServletResponse resp, int code, byte[] buf) {
		try {
			resp.setStatus(code);
			resp.setContentType("application/octet-stream");
			ServletOutputStream out = resp.getOutputStream();
			out.write(buf);
			out.flush();
			out.close();
		} catch(IOException e) {
			Log4j2Tool.error(ResponseUtils.class, "doResponse:", e);
		}
	}
}
